package com.freedom.web.mymvc.view.velocity;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.log.Log4JLogChute;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.runtime.resource.loader.JarResourceLoader;

import com.freedom.web.mymvc.pool.MyMVCRunnable;
import com.freedom.web.mymvc.utils.PropertiesUtils;

public class MyVelocityEngine {
	// logger
	private static final Logger logger = LogManager.getLogger(MyVelocityEngine.class);

	private MyVelocityEngine() {

	}

	// 单例模式
	private static VelocityEngine instance;

	/**
	 * Creates and configures the velocity engine.
	 *
	 * @param devMode
	 * @return
	 */
	private static VelocityEngine configureVelocityEngine(final boolean devMode) {
		// 这个是从别的开源软件里复制过来的，以前没怎么玩过velocity模板
		// 有需要进行参数优化的建议请联系: QQ 837500869,我会给你发红包.
		VelocityEngine engine = new VelocityEngine();
		engine.setProperty("resource.loader", "classpath, jar");
		engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		engine.setProperty("classpath.resource.loader.cache", !devMode);
		engine.setProperty("classpath.resource.loader.modificationCheckInterval", 5L);
		engine.setProperty("jar.resource.loader.class", JarResourceLoader.class.getName());
		engine.setProperty("jar.resource.loader.cache", !devMode);
		engine.setProperty("resource.manager.logwhenfound", false);
		engine.setProperty("input.encoding", "UTF-8");
		engine.setProperty("output.encoding", "UTF-8");
		engine.setProperty("directive.set.null.allowed", true);
		engine.setProperty("resource.manager.logwhenfound", false);
		engine.setProperty("velocimacro.permissions.allow.inline", true);
		engine.setProperty("velocimacro.library.autoreload", devMode);
		engine.setProperty("velocimacro.library", "/SystemVelocity/macros.vm");
		engine.setProperty("velocimacro.permissions.allow.inline.to.replace.global", true);
		engine.setProperty("velocimacro.arguments.strict", true);
		engine.setProperty("runtime.log.invalid.references", devMode);
		engine.setProperty("runtime.log.logsystem.class", Log4JLogChute.class);
		engine.setProperty("runtime.log.logsystem.log4j.logger", Logger.getLogger("org.apache.velocity.Logger"));
		engine.setProperty("parser.pool.size", 3);
		return engine;
	}

	static {
		boolean development = PropertiesUtils.getInstance().getDevelopMode() == 0 ? false : true;
		instance = configureVelocityEngine(development);
	}

	public static VelocityEngine getInstance() {
		return instance;
	}
}
